<template>
  <view v-for="(item, index) in arr" :key="index">
    <checkbox
      @click="singleCheck(index)"
      :label="item.name"
      :key="item.id"
      :checked="item.checked"
    ></checkbox>
    <text>{{ item.name }}</text>
    <text>￥{{ item.price }}</text>
    <button size="mini">-</button>
    <text>{{ item.count }}</text>
    <button @click="add(index)" size="mini">+</button>
  </view>

  全选<checkbox @click="toggleAll" :checked="totalCheck"></checkbox>
  <view> 总价:{{ total }} </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
let arr = [
  { id: 1001, name: "西游记", price: 10, count: 5, checked: true },
  { id: 1002, name: "红楼梦", price: 20, count: 2, checked: true },
  { id: 1003, name: "水浒传", price: 30, count: 2, checked: true },
  { id: 1004, name: "三国演义", price: 10, count: 2, checked: true },
];

arr = reactive(arr);

// let total = computed(() => {
//   return arr.reduce((total, item, index, arr) => {
//     return (total += item.price * item.count);
//   }, 0);
// });

let total = computed({
  get() {
    return arr.reduce((total, item) => {
      if (item.checked) {
        return (total += item.price * item.count);
      } else {
        return total;
      }
    }, 0);
  },
  set(val) {
    console.log(val);
  },
});

// let totalCheck = computed({
//   get() {
//     return arr.every((item) => item.checked);
//   },
//   set(val) {
//     console.log(val);
//   },
// });

let totalCheck = ref(true);
watch(
  arr,
  (newValue) => {
    totalCheck.value = newValue.every((item) => item.checked);
  },
  { deep: true }
);
//点击全选复选框
const toggleAll = function () {
  console.log(totalCheck.value, "###");
  totalCheck.value = !totalCheck.value;
  arr.forEach((item) => {
    item.checked = totalCheck.value;
  });
};

const add = function (index: number) {
  arr[index].count += 1;
};

const singleCheck = function (index: number) {
  arr[index].checked = !arr[index].checked;
};
</script>

<style style="less" scoped></style>
